package com.zhkj.txg.module.login.ui

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import com.zhkj.lib.base.AccountChangeEvent
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.R
import com.zhkj.txg.module.home.ui.MainActivity
import com.zhkj.txg.module.login.vm.LoginViewModel
import kotlinx.android.synthetic.main.activity_login.*


class LoginActivity : ViewModelActivity<LoginViewModel>() {

    companion object {
        private val TYPE = "type"
        private val TYPE_JUMP = 0
        private val TYPE_OPEN = 1
        fun open2Login(activity: Activity) {
            val intent = Intent(activity, LoginActivity::class.java).putExtra(TYPE, TYPE_OPEN)
            activity.startActivity(intent)
        }

        fun jump2Login(activity: Activity) {
            val intent = Intent(activity, LoginActivity::class.java).putExtra(TYPE, TYPE_JUMP)
            activity.startActivity(intent)
        }
    }

    private var currentFragment: Fragment? = null

    enum class Index {
        LOGIN,
        CAPTCHA,
        INVITE,
        REGISTER,
        HOME
    }

    private val loginFragment: LoginFragment by lazy {
        LoginFragment()
    }
    private val captchaFragment: CaptchaFragment by lazy {
        CaptchaFragment()
    }
    private val inviteFragment: InviteFragment by lazy {
        InviteFragment()
    }
    private val registerFragment: RegisterSuccessFragment by lazy {
        RegisterSuccessFragment()
    }
    private val requestCodeBind = 1009

    override val layoutResId = R.layout.activity_login
    override fun setViewModel(): LoginViewModel = createViewModel()
    override fun statusTitleBar(): View? = loginTitle

    override fun initViewModel() {
        // 页面跳转数据观察者
        viewModel.pageIndexLiveData.observe(this, Observer {
            when (it ?: Index.LOGIN) {
                Index.LOGIN -> {
                    setLoginTitleBar()
                    startFragment(loginFragment, false)
                }
                Index.CAPTCHA -> {
                    setCaptchaTitleBar()
                    startFragment(captchaFragment, true)
                }
                Index.INVITE -> {
                    setInviteTitleBar()
                    startFragment(inviteFragment, true)
                }
                Index.REGISTER -> {
                    setRegisterTitleBar()
                    startFragment(registerFragment, true)
                }
                Index.HOME -> {
                    jumpOrFinish()
                }
            }
        })
        // 三方登录授权信息数据观察者
        viewModel.thirdLoginResultSubscribe().observe(this, Observer {
            // 调用三方登录接口进行登录
            if (it.success) viewModel.thirdLogin("wechat", it.code)
        })
        // 三方登录数据观察者
        viewModel.thirdLoginLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip, true)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { data ->
                data.userInfo?.let {
                    if (data.isBindMobile) {
                        // 保存登录数据
                        AccountManager.saveToken(it.token)
                        AccountManager.saveUserId(it.user_id.toLong())
                        // 跳转登录页面
                        viewModel.pageIndexLiveData.value = Index.HOME
                    } else {
                        // 跳转绑定手机页面
                        BindMobileActivity.loginBind(this, it.token, it.user_id.toLong(), requestCodeBind)
                    }
                }
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == requestCodeBind && resultCode == RESULT_OK) jumpOrFinish()
    }

    override fun initData() {
        viewModel.pageIndexLiveData.value = Index.LOGIN
    }

    override fun onBackPressed() {
        if (supportFragmentManager.backStackEntryCount > 0) {
            backFragment()
        } else super.onBackPressed()
    }

    /**
     * 显示对应的Fragment
     * @param fragment 要显示的fragment
     * @param canGoBack 是否要加入回退栈
     */
    private fun startFragment(fragment: Fragment, canGoBack: Boolean) {
        if (currentFragment == fragment) {
            return
        }
        with(supportFragmentManager.beginTransaction()) {
            replace(R.id.loginContainer, fragment)
            setMaxLifecycle(fragment, Lifecycle.State.STARTED)
            if (canGoBack) addToBackStack(null)
            commit()
        }
        currentFragment = fragment
    }

    /**
     * 设置登录Fragment的TitleBar显示内容
     */
    private fun setLoginTitleBar() {
        loginTitle.showLeft(false).showRight(true)
            .setRightTextContent(resources.getString(R.string.skip_login))
            .setRightTextColor(
                ContextCompat.getColorStateList(
                    this,
                    R.color.colorLightText
                )
            ).setRightClickListener(View.OnClickListener {
                // 将类型变为打开首页,再跳转
                if (intent.getIntExtra(TYPE, TYPE_OPEN) == TYPE_JUMP) finish()
                else jumpOrFinish()
            })
    }

    /**
     * 设置验证码Fragment的TitleBar显示内容
     */
    private fun setCaptchaTitleBar() {
        loginTitle.showLeft(true).showRight(true)
            .setLeftIcon(R.drawable.ic_arrow_left_black)
            .setRightTextContent(resources.getString(R.string.send_code_again))
            .setRightTextColor(
                ContextCompat.getColorStateList(
                    this,
                    R.color.colorDeepText
                )
            ).setLeftClickListener(View.OnClickListener {
                backFragment()
            }).setRightClickListener(View.OnClickListener {
                viewModel.sendCode(viewModel.mobile2GetCode)
            })
    }

    /**
     * 设置邀请码Fragment的TitleBar显示内容
     */
    private fun setInviteTitleBar() {
        loginTitle.showLeft(true).showRight(false).setLeftClickListener(View.OnClickListener {
            backFragment()
        })
    }

    /**
     * 设置注册成功Fragment的TitleBar显示内容
     */
    private fun setRegisterTitleBar() {
        loginTitle.showLeft(true).showRight(false).setLeftClickListener(View.OnClickListener {
            backFragment()
        })
    }

    /**
     * Fragment回退
     */
    private fun backFragment() {
        supportFragmentManager.popBackStack()
        when (supportFragmentManager.backStackEntryCount - 1) {
            Index.LOGIN.ordinal -> {
                setLoginTitleBar()
                currentFragment = loginFragment
            }
            Index.CAPTCHA.ordinal -> {
                setCaptchaTitleBar()
                currentFragment = captchaFragment
            }
            Index.INVITE.ordinal -> {
                setInviteTitleBar()
                currentFragment = inviteFragment
            }
            Index.REGISTER.ordinal -> {
                setRegisterTitleBar()
                currentFragment = registerFragment
            }
        }
    }

    /**
     * 判断是跳转到首页还是单纯关闭登录页
     */
    private fun jumpOrFinish() {
        val type = intent.getIntExtra(TYPE, TYPE_OPEN)
        if (type == TYPE_OPEN) {
            val intent = Intent(this, MainActivity::class.java)
                .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(intent)
        } else RxBus.post(AccountChangeEvent())
        finish()
    }
}